<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>完整修复验证测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }

        .test-section {
            background: rgba(255, 255, 255, 0.1);
            margin: 20px 0;
            padding: 20px;
            border-radius: 10px;
            backdrop-filter: blur(10px);
        }

        button {
            background: #4CAF50;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            margin: 5px;
        }

        button:hover {
            background: #45a049;
        }

        button:disabled {
            background: #666;
            cursor: not-allowed;
        }

        .log {
            background: rgba(0, 0, 0, 0.3);
            padding: 10px;
            border-radius: 5px;
            height: 400px;
            overflow-y: auto;
            font-family: monospace;
            font-size: 12px;
        }

        .input-group {
            margin: 10px 0;
        }

        .input-group label {
            display: block;
            margin-bottom: 5px;
        }

        .input-group input {
            width: 100%;
            padding: 8px;
            border: none;
            border-radius: 4px;
            margin-bottom: 10px;
        }

        .success {
            color: #4CAF50;
        }

        .error {
            color: #f44336;
        }

        .info {
            color: #2196F3;
        }

        .warning {
            color: #ff9800;
        }

        .grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        .status {
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
        }

        .connected {
            background: rgba(76, 175, 80, 0.3);
            border: 1px solid #4CAF50;
        }

        .disconnected {
            background: rgba(244, 67, 54, 0.3);
            border: 1px solid #f44336;
        }
    </style>
</head>

<body>
    <h1>🎯 完整修复验证测试</h1>

    <div class="test-section">
        <h2>🔧 修复内容总结</h2>
        <ul>
            <li>✅ 修复了连接状态检查逻辑，现在正确显示"已连接"状态</li>
            <li>✅ 修复了玩家重复加入房间的问题</li>
            <li>✅ 改进了JoinGameCommandHandler的逻辑</li>
            <li>✅ 添加了玩家是否已在房间中的检查</li>
            <li>✅ 修复了前端玩家ID匹配逻辑</li>
            <li>✅ 改进了toggleReady方法的玩家查找逻辑</li>
            <li>✅ 修复了Guid解析错误</li>
        </ul>
    </div>

    <div class="grid">
        <div class="test-section">
            <h2>🔌 连接测试</h2>
            <div class="input-group">
                <label>房间码:</label>
                <input type="text" id="roomCode" value="GAGZJ4" />
            </div>
            <div class="input-group">
                <label>玩家昵称:</label>
                <input type="text" id="playerName" value="小狗" />
            </div>
            <button onclick="testConnection()">连接并加入房间</button>
            <button onclick="disconnect()">断开连接</button>
            <div id="connectionStatus" class="status disconnected">未连接</div>
        </div>

        <div class="test-section">
            <h2>🎮 功能测试</h2>
            <button onclick="testReadyFunction()" id="readyBtn" disabled>测试准备功能</button>
            <button onclick="testDuplicateJoin()" id="duplicateBtn" disabled>测试重复加入</button>
            <button onclick="testAPI()" id="apiBtn" disabled>测试API接口</button>
            <div id="roomStatus" class="status">未加入房间</div>
        </div>
    </div>

    <div class="test-section">
        <h2>📊 状态信息</h2>
        <div id="statusInfo"></div>
    </div>

    <div class="test-section">
        <h2>📝 实时日志</h2>
        <div id="log" class="log"></div>
        <button onclick="clearLog()">清空日志</button>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/6.0.1/signalr.min.js"></script>
    <script>
        let connection = null;
        let currentRoomCode = null;
        let currentPlayerName = null;
        let isConnected = false;

        function log(message, type = 'info') {
            const logDiv = document.getElementById('log');
            const timestamp = new Date().toLocaleTimeString();
            const className = type;
            logDiv.innerHTML += `<div class="${className}">[${timestamp}] ${message}</div>`;
            logDiv.scrollTop = logDiv.scrollHeight;
        }

        function clearLog() {
            document.getElementById('log').innerHTML = '';
        }

        function updateConnectionStatus(connected) {
            const statusDiv = document.getElementById('connectionStatus');
            if (connected) {
                statusDiv.className = 'status connected';
                statusDiv.textContent = '已连接';
            } else {
                statusDiv.className = 'status disconnected';
                statusDiv.textContent = '未连接';
            }
            isConnected = connected;
        }

        function updateRoomStatus(status) {
            document.getElementById('roomStatus').textContent = status;
        }

        function updateStatusInfo() {
            const statusDiv = document.getElementById('statusInfo');
            statusDiv.innerHTML = `
                <h3>当前状态</h3>
                <p><strong>连接状态:</strong> ${isConnected ? '已连接' : '未连接'}</p>
                <p><strong>房间码:</strong> ${currentRoomCode || '未设置'}</p>
                <p><strong>玩家昵称:</strong> ${currentPlayerName || '未设置'}</p>
                <p><strong>localStorage玩家昵称:</strong> ${localStorage.getItem('playerName') || '未设置'}</p>
            `;
        }

        function enableButtons() {
            document.getElementById('readyBtn').disabled = false;
            document.getElementById('duplicateBtn').disabled = false;
            document.getElementById('apiBtn').disabled = false;
        }

        async function testConnection() {
            try {
                const url = 'http://localhost:5152/gamehub';
                log(`正在连接SignalR: ${url}`, 'info');

                connection = new signalR.HubConnectionBuilder()
                    .withUrl(url)
                    .withAutomaticReconnect()
                    .build();

                // 设置事件处理器
                connection.on('PlayerJoined', (player) => {
                    log(`玩家加入: ${player.nickName || player.NickName}`, 'success');
                });

                connection.on('PlayerLeft', (playerId) => {
                    log(`玩家离开: ${playerId}`, 'warning');
                });

                connection.on('PlayerReady', (playerId, ready) => {
                    log(`玩家准备状态: ${playerId} = ${ready}`, 'info');
                });

                connection.on('GameJoined', (game) => {
                    log(`游戏状态更新: ${game.code || game.Code}`, 'success');
                });

                connection.on('Error', (error) => {
                    log(`错误: ${error}`, 'error');
                });

                await connection.start();
                updateConnectionStatus(true);
                log('SignalR连接成功', 'success');

                // 加入房间
                currentRoomCode = document.getElementById('roomCode').value;
                currentPlayerName = document.getElementById('playerName').value;

                log(`加入房间: ${currentRoomCode}, 玩家: ${currentPlayerName}`, 'info');
                await connection.invoke('JoinGame', currentRoomCode, currentPlayerName, null);
                updateRoomStatus(`已加入房间: ${currentRoomCode}`);
                log('成功加入房间', 'success');

                enableButtons();
                updateStatusInfo();
            } catch (error) {
                log(`连接失败: ${error.message}`, 'error');
                updateConnectionStatus(false);
            }
        }

        async function disconnect() {
            if (connection) {
                try {
                    await connection.stop();
                    connection = null;
                    updateConnectionStatus(false);
                    updateRoomStatus('已断开连接');
                    log('已断开连接', 'info');

                    // 禁用按钮
                    document.getElementById('readyBtn').disabled = true;
                    document.getElementById('duplicateBtn').disabled = true;
                    document.getElementById('apiBtn').disabled = true;
                } catch (error) {
                    log(`断开连接失败: ${error.message}`, 'error');
                }
            }
        }

        async function testReadyFunction() {
            if (!connection || !currentRoomCode || !currentPlayerName) {
                log('请先连接并加入房间', 'error');
                return;
            }

            try {
                log('测试准备功能...', 'info');
                await connection.invoke('SetReady', currentRoomCode, currentPlayerName, true);
                log('✅ 准备功能测试成功', 'success');
            } catch (error) {
                log(`❌ 准备功能测试失败: ${error.message}`, 'error');
            }
        }

        async function testDuplicateJoin() {
            if (!connection || !currentRoomCode || !currentPlayerName) {
                log('请先连接并加入房间', 'error');
                return;
            }

            try {
                log('测试重复加入功能...', 'info');
                await connection.invoke('JoinGame', currentRoomCode, currentPlayerName, null);
                log('✅ 重复加入功能测试成功（应该不会报错）', 'success');
            } catch (error) {
                log(`❌ 重复加入功能测试失败: ${error.message}`, 'error');
            }
        }

        async function testAPI() {
            try {
                log('测试API接口...', 'info');

                // 测试获取游戏列表
                const listResponse = await fetch('http://localhost:5152/api/game/list');
                const listData = await listResponse.json();
                log(`游戏列表API测试成功: ${listData.length} 个游戏`, 'success');

                // 测试获取特定房间信息
                if (currentRoomCode) {
                    const roomResponse = await fetch(`http://localhost:5152/api/game/code/${currentRoomCode}`);
                    const roomData = await roomResponse.json();
                    log(`房间信息API测试成功: ${roomData.code || roomData.Code}`, 'success');
                }

                log('✅ 所有API接口测试成功', 'success');
            } catch (error) {
                log(`❌ API接口测试失败: ${error.message}`, 'error');
            }
        }

        // 页面加载时初始化
        window.onload = function () {
            log('完整修复验证测试页面已加载', 'info');
            log('请确保后端服务在 http://localhost:5152 运行', 'warning');
            updateStatusInfo();
        };
    </script>
</body>

</html>